<?php 

final class Application{

	public static function run(){
		//初始化框架
		self::_init();
		//接收错误内容
		set_error_handler(array(__CLASS__,'error'));
		register_shutdown_function(array(__CLASS__,'fatal_error'));
		//加载公共文件里面的文件（类，方法）
		self::_import_commonlib();
		//设置web路径
		self::_set_url();
		//自动载入类
		spl_autoload_register(array(__CLASS__,'_autoload'));
		//创建demo
		self::_create_demo_copy();
		//self::_create_demo();
		//运行框架
		self::_app_run();
	}

	/**
	 * [fatal_error 致命性错误]
	 * @return [type] [description]
	 */
	public static function fatal_error(){
		if($err = error_get_last()){
			self::error($err['type'],$err['message'],$err['file'],$err['line']);
		}
	}

	/**
	 * [error 接收错误信息，美化错误页面展示]
	 * @param  [type] $errno [错误级别]
	 * @param  [type] $error [错误内容]
	 * @param  [type] $file  [文件]
	 * @param  [type] $line  [行号]
	 * @return [type]        [description]
	 */
	public static function error($errno,$error,$file,$line){
		switch ($errno) {
			case E_ERROR:
			case E_PARSE:
			case E_CORE_ERROR:
			case E_COMPILE_ERROR:
			case E_USER_ERROR:
				 $msg = $error.$file."第{$line}行";
				 halt($msg);
				 break;
			case E_STRICT:
			case E_USER_WARNING:
			case E_USER_NOTICE:
			default:
				if(DEBUG){
					include SYSTEM_DATA_PATH.'/Tpl/notice.html';
				}
				break;
		}
	}

	private static function _app_run(){
		$c = isset($_GET[C('VAR_CONTROLLER')]) ? $_GET[C('VAR_CONTROLLER')] : 'Index';
		$a = isset($_GET[C('VAR_ACTION')]) ? $_GET[C('VAR_ACTION')] : 'Index';

		define("CONTROLLER",$c);
		define("ACTION",$a);

		$c .= 'Controller';

		if(class_exists($c)){ //判断当前类是否存在
			$obj = new $c(); //实例化操作
			if(!method_exists($obj, $a)){
				if(method_exists($obj,'__empty')){
					$obj->__empty(); //调用方法
				}else{
					halt($c.'控制器中'.$a.'方法不存在！');
				}
			}else{
				$obj->$a(); //调用方法
			}
		}else{
			$obj = new EmptyController();
			$obj->index();
		}
	}

	/**
	 * [_create_demo_copy 将写好的文件放入到指定文件中]
	 * @return [type] [description]
	 */
	private static function _create_demo_copy(){
		file_exists(APP_INDEX_PATH."/Index.html") || copy(SYSTEM_DATA_PATH.'/Tpl/index.html',APP_INDEX_PATH."/Index.html");
		file_exists(APP_CONTROLLER_PATH."/IndexController.class.php")||copy(SYSTEM_DATA_PATH.'/Tpl/IndexController.class.php',APP_CONTROLLER_PATH."/IndexController.class.php");
	}


	/**
	 * [_create_demo 创建demo]
	 * @return [type] [description]
	 */
	private static function _create_demo(){
		$path = APP_CONTROLLER_PATH.'/IndexController.class.php';
		$str = <<<str
<?php
class IndexController extends Controller{
	public function Index(){
		echo "<h2>欢迎使用西月框架</h2>";
	}
}
?>		
str;

		file_exists($path) || file_put_contents($path,$str);
	} 

	/**
	 * [_autoload 自动载入类]
	 * @return [type] [description]
	 */
	private static function _autoload($className){
		switch (true) {
			//判断是否是控制器
			case strlen($className) > 10 && substr($className,-10) == 'Controller':
				$path = APP_CONTROLLER_PATH.'/'.$className.".class.php";
				if(!file_exists($path)){
					$emptyPath = APP_CONTROLLER_PATH.'/EmptyController.class.php';
					if(file_exists($emptyPath)){
						include $emptyPath;
						return;
					}else{
						halt($path.'控制器未找到');
					}
				}
				include $path;
				break;
			case strlen($className) > 5 && substr($className,-5) == 'Model':
				$path = COMMON_MODEL_PATH.'/'.$className.".class.php";
				if(!file_exists($path)){
					halt($path.'模型未找到');
				}
				include $path;
				break;	
			default:
				$path = EXTENDS_TOOL_PATH.'/'.$className.".class.php";
				if(!file_exists($path)) halt($path.'类未找到');
				include $path;
				break;
		}
	}

	/**
	 * [_set_url 设置web路径]
	 */
	private static function _set_url(){
		$path = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
		$path = str_replace('\\',"/",$path);
		define('__APP__',$path);
		define('__ROOT__',dirname(__APP__));
		define('__TPL__',__ROOT__.'/'.APP_NAME.'/Tpl');
		define('__PUBLIC__',__TPL__.'/Public');
	}

	/**
	 * [_init 初始化框架]
	 * @return [type] [description]
	 */
	private static function _init(){
		//加载系统配置项
		C(include SYSTEM_CONFIG_PATH.'/Config.php');

		//加载公共配置项
		$commonPath = COMMON_CONFIG_PATH.'/Config.php';

		$CommonConfig = <<<str
<?php
	return array(
		//配置项 => 配置值
		//链接数据库
		'DB_CHARSET'		=> 'utf8',
		'DB_HOST'			=> '127.0.0.1',
		'DB_PORT'			=> 3306,
		'DB_USER'			=> 'root',
		'DB_PASSWORD'		=> '',
		'DB_DATABASE'		=> '',
		'DB_PREFIX'			=> '',
	);
?>
str;

		file_exists($commonPath) || file_put_contents($commonPath, $CommonConfig);
		//加载公共配置项
		C(include $commonPath);

		//用户配置项
		$userPath = APP_CONFIG_PATH.'/Config.php';

		$userConfig = <<<str
<?php
	return array(
		//配置项 => 配置值
	);
?>
str;
		
		file_exists($userPath) || file_put_contents($userPath, $userConfig);
		//加载用户配置项
		C(include $userPath);

		//设置默认时区
		date_default_timezone_set(C('DEFAULT_TIME_ZONE'));

		C('SESSION_AUTO_START') && session_start();

		//定义版本信息
		define('XY_VERSION',C('XY_VERSION'));
	}

	/**
	 * [_import_commonlib 加载公共文件夹下面的Lib方法和类]
	 * @return [type] [description]
	 */
	private static function _import_commonlib(){
		$fileArr = C('AUTO_LOAD_FILE');
		if(is_array($fileArr) && !empty($fileArr)){
			foreach ($fileArr as $v) {
				require_once COMMON_LIB_PATH.'/'.$v;
			}
		}
	}
}
?>